﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace JGSY.LHBS
{
    public partial class FrmNameManage : Form
    {
        public FrmNameManage()
        {
            InitializeComponent();
        }
        //名目文件路径
        string filePath = CommonHelper.itemPath;
        int actType = 1;//提交状态  1 新增   2 修改
        string[] currentItem = new string[3];//当前选择名目信息
        int selIndex = -1;//选择项的索引
        string wSpace = "        ";//列间隔
        //名目列表
        Dictionary<int, string> itemList = new Dictionary<int, string>();
        private void FrmNameManage_Load(object sender, EventArgs e)
        {
            cbSelect.SelectedIndex = 0;//默认选择收入
            actType = 1;
            lbViewData.Items.Clear();
            if (string.IsNullOrEmpty(filePath))
            {
                MessageHelper.Error("名目加载", "名目文件路径并没有配置！");
                //禁用界面功能
                foreach (Control c in this.Controls)
                {
                    c.Enabled = false;
                }
                return;
            }
            //加载已有名目列表
            //读取名目文件中的所有行
            List<string> lines = TextHelper.ReadTextAllLines(filePath);
            //大于1行才有数据
            if (lines.Count > 1)
            {
                for (int i = 1; i < lines.Count; i++)
                {
                    //编号;类型;名称
                    string[] arr = lines[i].Split(';');
                    lbViewData.Items.Add(arr[0] + wSpace + arr[1] + wSpace + arr[2]);
                    itemList.Add(int.Parse(arr[0]), lines[i]);
                }
            }
        }

 

        private void btAddOrUpdate_Click(object sender, EventArgs e)
        {
            //信息接收
            int id = 0;
            //int.TryParse(txtItemId.Text.Trim(), out id);
            if (!string.IsNullOrEmpty(tbNo.Text))
                id = Convert.ToInt32(tbNo.Text.Trim());
            string type = cbSelect.Text.Trim();
            string itemName = tbName.Text.Trim();
            //信息检查
            if (id == 0)
            {
                MessageHelper.Error("名目提交", "名目编号不能为空！");
                tbNo.Focus();
                return;
            }
            else if (actType == 1 && itemList.ContainsKey(id))
            {
                MessageHelper.Error("名目提交", "名目编号已存在！");
                tbNo.Focus();
                return;
            }
            if (string.IsNullOrEmpty(itemName))
            {
                MessageHelper.Error("名目提交", "名目名称不能为空！");
                tbName.Focus();
                return;
            }
            else if (actType == 1 && ExistItemName(itemName))
            {
                MessageHelper.Error("名目提交", "名目名称已存在！");
                tbName.Focus();
                return;
            }
            //提交：1 新增   ---  写入文件 并加载名目信息    2修改  更新到名目列表
            if (actType == 1)//新增
            {
                //不存在，创建，并写入列标题
                if (!File.Exists(filePath))
                {
                    TextHelper.WriteMsg("编号;类型;名称", filePath, false);//创建文件，写文本
                }
                //写入文件 
                TextHelper.WriteMsg(id + ";" + type + ";" + itemName, filePath, true);//末尾追加
                //添加名目到列表框中
                lbViewData.Items.Add(id + wSpace + type + wSpace + itemName);
                //添加名目数据列表中
                itemList.Add(id, id + ";" + type + ";" + itemName);
            }
            else //修改
            {
                itemList[id] = id + ";" + type + ";" + itemName;//更新列表名目数据列表中
                //在原来的位置插入更新后的信息
                lbViewData.Items.Insert(selIndex, id + wSpace + type + wSpace + itemName);
                lbViewData.Items.RemoveAt(selIndex + 1);//移除原来的信息
            }
        }
        /// <summary>
        /// 判断名目名称是否存在
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private bool ExistItemName(string name)
        {
            foreach (int key in itemList.Keys)
            {
                string val = itemList[key];
                string iName = val.Split(';')[2];
                if (iName == name)
                {
                    return true;
                }
            }
            return false;
        }
        private void btClear_Click(object sender, EventArgs e)
        {
            ClearInfo();
        }
    private    void ClearInfo()
        {
            tbNo.Text = "";
            tbName.Text = "";
            cbSelect.SelectedIndex = 0;
            currentItem = new string[3];
            tbNo.Enabled = true;
            btAddOrUpdate.Text = "新增";
            actType = 1;
        }

        private void btSave_Click(object sender, EventArgs e)
        {
            if (actType != 1 && itemList.Count > 0)
            {
                List<string> msgList = new List<string>();
                TextHelper.WriteMsg("编号;类型;名称", filePath, false);
                lbViewData.Items.Clear();
                var list = itemList.OrderBy(kv => kv.Key);
                foreach (var kv in list)
                {
                    string val = kv.Value;
                    string[] arr = val.Split(';');
                    msgList.Add(val);
                    lbViewData.Items.Add(arr[0] + wSpace + arr[1] + wSpace + arr[2]);
                }
                TextHelper.WriteMsgList(msgList, filePath, true);
                MessageHelper.Info("保存名目", "名目信息保存成功！");
            }
        }

        private void btDelete_Click(object sender, EventArgs e)
        {
            //选择的项集合
            var selList = lbViewData.SelectedItems;
            if (selList.Count > 0)
            {
                DialogResult dr = MessageHelper.Confirm("删除名目", "你确定要删除选择名目信息吗？");
                if (dr == DialogResult.OK)
                {
                    List<string> selItems = new List<string>();
                    foreach (string item in selList)
                    {
                        selItems.Add(item);
                    }
                    //移除选择的项
                    int i = 0;
                    while (i < selItems.Count)
                    {
                        int id = int.Parse(selItems[i].Substring(0, 3));
                        //从列表框中移除
                        lbViewData.Items.Remove(selItems[i]);
                        //从名目数据列表中移除
                        itemList.Remove(id);
                        if (currentItem[0] == id.ToString())
                        {
                            ClearInfo();
                        }
                        i++;
                    }
                    actType = 1;//删除
                    MessageHelper.Info("删除名目", "选择的名目信息删除成功！");
                }
            }
        }

        private void lbViewData_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lbViewData.SelectedItems.Count > 0)
            {
                //选择的项
                string selItem = lbViewData.SelectedItems[0].ToString();
                //101  102 ....
                int id = int.Parse(selItem.Substring(0, 3));
                string strItem = itemList[id];//名目信息
                currentItem = strItem.Split(';');//当前名目信息数组
                tbNo.Text = currentItem[0];
                tbName.Text = currentItem[2];
                cbSelect.Text = currentItem[1];
                tbNo.Enabled = false;
                actType = 2;//修改
                btAddOrUpdate.Text = "修改";
                selIndex = lbViewData.SelectedIndices[0];//选择项的索引
            }
        }
    }
}
